package com.example.demo.controller;

import com.example.demo.model.ApiResponse;
import com.example.demo.model.LoginResponse;
import com.example.demo.model.User;
import com.example.demo.service.AuthService;
import com.example.demo.model.ApiResponse;
import com.example.demo.model.LoginResponse;
import com.example.demo.model.User;
import com.example.demo.service.AuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<String>> register(@RequestBody User user) {
        try {
            String result = authService.register(user);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            logger.error("注册失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "注册失败: " + e.getMessage()));
        }
    }

    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@RequestBody User user) {
        LoginResponse loginResponse = authService.login(user.getUsername(), user.getPassword());
        return ResponseEntity.ok(ApiResponse.success(loginResponse));
    }
}